package com.wiz.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import com.google.protobuf.ByteString;
import com.wiz.netty.message.NettyMessageTO;

public class FileUtil {
	/**
	 * 读取源文件内容
	 * @param filename String 文件路径
	 * @throws IOException
	 * @return byte[] 文件内容
	 */
	public static byte[] readFile(String filename) throws IOException {

		File file = new File(filename);
		if (filename == null || filename.equals("")) {
			throw new NullPointerException("无效的文件路径");
		}
		long len = file.length();
		byte[] bytes = new byte[(int) len];

		BufferedInputStream bufferedInputStream = new BufferedInputStream(
				new FileInputStream(file));
		int r = bufferedInputStream.read(bytes);
		if (r != len){
			throw new IOException("读取文件不正确");
		}
		bufferedInputStream.close();
		return bytes;
	}

	/**
	 * 将数据写入文件
	 * @param data byte[]
	 * @throws IOException
	 */
	public static void writeFile(byte[] data, String filename)
			throws IOException {
		File file = new File(filename);
		file.getParentFile().mkdirs();
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
				new FileOutputStream(file));
		bufferedOutputStream.write(data);
		bufferedOutputStream.close();

	}

	/**
	 * 从jar文件里读取class
	 * @param filename String
	 * @throws IOException
	 * @return byte[]
	 */
	public byte[] readFileJar(String filename) throws IOException {
		BufferedInputStream bufferedInputStream = new BufferedInputStream(
				getClass().getResource(filename).openStream());
		int len = bufferedInputStream.available();
		byte[] bytes = new byte[len];
		int r = bufferedInputStream.read(bytes);
		if (len != r) {
			bytes = null;
			throw new IOException("读取文件不正确");
		}
		bufferedInputStream.close();
		return bytes;
	}

	/**
	 * 读取网络流，为了防止中文的问题，在读取过程中没有进行编码转换，而且采取了动态的byte[]的方式获得所有的byte返回
	 * @param bufferedInputStream BufferedInputStream
	 * @throws IOException
	 * @return byte[]
	 */
	public byte[] readUrlStream(BufferedInputStream bufferedInputStream)
			throws IOException {
		byte[] bytes = new byte[100];
		byte[] bytecount = null;
		int n = 0;
		int ilength = 0;
		while ((n = bufferedInputStream.read(bytes)) >= 0) {
			if (bytecount != null)
				ilength = bytecount.length;
			byte[] tempbyte = new byte[ilength + n];
			if (bytecount != null) {
				System.arraycopy(bytecount, 0, tempbyte, 0, ilength);
			}
			System.arraycopy(bytes, 0, tempbyte, ilength, n);
			bytecount = tempbyte;
			if (n < bytes.length){
				break;
			}
		}
		return bytecount;
	}
	
	 /** 
     * 数组转对象 
     * @param bytes 
     * @return 
     */  
    public static Object toObject (byte[] bytes) {     
        Object obj = null;     
        try {       
            ByteArrayInputStream bis = new ByteArrayInputStream (bytes);       
            ObjectInputStream ois = new ObjectInputStream (bis);       
            obj = ois.readObject();     
            ois.close();  
            bis.close();  
        } catch (IOException ex) {       
            ex.printStackTrace();  
        } catch (ClassNotFoundException ex) {       
            ex.printStackTrace();  
        }     
        return obj;   
    }  
    
    static final char[] HEX = "0123456789ABCDEF".toCharArray();
    
    /**
	 * byte[]转16进制字符串
	 * @param buffer
	 * @param start
	 * @param length
	 * @return
	 */
	public static String hexEncode(byte[] buffer, int start, int length) {
		if (buffer.length == 0) {
			return "";
		}
		int holder = 0;
		char[] chars = new char[length * 2];
        int pos = -1;
		for (int i = start; i < start+length; i++) {
			holder = (buffer[i] & 0xf0) >> 4;
			chars[++pos * 2] = HEX[holder];
			holder = buffer[i] & 0x0f;
			chars[(pos * 2) + 1] = HEX[holder];
		}
		return new String(chars);
	}
	
	/**
	 * 16进制字符串转byte[]
	 * @param hex
	 * @return
	 */
	public static byte[] hexDecode(String hex) {
		//A null string returns an empty array
		if (hex == null || hex.length() == 0) {
			return new byte[0];
		} else if (hex.length() < 3) {
			return new byte[]{ (byte)(Integer.parseInt(hex, 16) & 0xff) };
		}
		//Adjust accordingly for odd-length strings
		int count = hex.length();
		int nibble = 0;
		if (count % 2 != 0) {
			count++;
			nibble = 1;
		}
		byte[] buf = new byte[count / 2];
		char c = 0;
		int holder = 0;
		int pos = 0;
		for (int i = 0; i < buf.length; i++) {
		    for (int z = 0; z < 2 && pos<hex.length(); z++) {
		        c = hex.charAt(pos++);
		        if (c >= 'A' && c <= 'F') {
		            c -= 55;
		        } else if (c >= '0' && c <= '9') {
		            c -= 48;
		        } else if (c >= 'a' && c <= 'f') {
		            c -= 87;
		        }
		        if (nibble == 0) {
		            holder = c << 4;
		        } else {
		            holder |= c;
		            buf[i] = (byte)holder;
		        }
		        nibble = 1 - nibble;
		    }
		}
		return buf;
	}
	
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		NettyMessageTO.MessageContent.Builder builder = NettyMessageTO.MessageContent.newBuilder();
		builder.setIden(ByteString.copyFrom(new byte[]{1}));
		builder.setMab(ByteString.copyFrom(new byte[]{1}));
		builder.setMac(ByteString.copyFrom(new byte[]{1}));
		builder.setMti(ByteString.copyFrom(new byte[]{1}));
		builder.setType(1);
		NettyMessageTO.MessageContent nettyMessage = builder.build();
		String file = "F:\\1.txt";
//		byte[] bs = FileUtil.readFile(file);
		byte[] bs = FileUtil.hexDecode("0A0301020310011A030B0C0D22030405062A03070809");
		NettyMessageTO.MessageContent.Builder builder2 = NettyMessageTO.MessageContent.newBuilder();
		builder2.mergeFrom(bs);
		NettyMessageTO.MessageContent message = builder2.build();
		System.out.println(message.getType());
	}
}
